﻿using indice.Edi;
using indice.Edi.Serialization;
using NPOI.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cyss.Core.Helper
{
    /// <summary>
    /// EDI 文件帮助类
    /// </summary>
    public class EdiHelper
    {
        public static T Deserialize<T>(string fileName)
        {
            var grammar = EdiGrammar.NewX12();
            var interchange = default(T);
            using (var stream = new StreamReader(fileName))
            {
                interchange = new EdiSerializer().Deserialize<T>(stream, grammar);
            }
            return interchange;
        }

        public static string Serialize(object obj)
        {
            var grammar = EdiGrammar.NewX12();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//构建字节输出流
            using (var textWriter = new StreamWriter(outputStream))
            {
                using (var ediWriter = new EdiTextWriter(textWriter, grammar))
                {
                    new EdiSerializer().Serialize(ediWriter, obj);
                }
            }
            string myStr = System.Text.Encoding.UTF8.GetString(outputStream.ToByteArray());
            return myStr;
        }

        /// <summary>
        /// 获取EDI消息类型
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetEdiType(string fileName)
        {
            var sT = Deserialize<EDI_ST>(fileName);
            return sT.IdentifierCode;
        }

        [EdiSegment, EdiPath("ST")]
        private class EDI_ST
        {
            [EdiValue("9(3)", Path = "ST/0", Description = "Transaction Set Identifier Code")]
            public string IdentifierCode { set; get; }

            [EdiValue("9(4)", Path = "ST/1", Description = "Transaction Set Control Number")]
            public string ControlNumbers { set; get; }
        }
    }
}
